#include<vector>
#include<unordered_set>
#include<deque>
using namespace std;
class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        if (matrix.size() < 1) return matrix;
        int rows = matrix.size();
        int cols = matrix[0].size();
        unordered_set<int>visited;
        deque<pair<int, int>> queue;
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                if (matrix[i][j] == 0) {
                    queue.push_back(make_pair(i, j));
                    visited.insert(i * cols + j);
                }
            }
        }
        int action[][2] = { {-1,0},{1,0},{0,-1},{0,1} };
        while (!queue.empty()) {
            int size = queue.size();
            while (size > 0) {
                --size;
                auto p = queue.front();
                queue.pop_front();
                for (int i = 0; i < 4; ++i) {
                    int new_row = p.first + action[i][0];
                    int new_col = p.second + action[i][1];
                    if (new_row >= 0 && new_row < rows && new_col >= 0 && new_col < cols
                        &&visited.find(new_row* cols +new_col)==visited.end()) {
                        matrix[new_row][new_col] = matrix[p.first][p.second] + 1;
                        visited.insert(new_row * cols + new_col);
                        queue.push_back(make_pair(new_row, new_col));
                    }
                }
            }
        }
        return matrix;
    }
};